package top.jacktgq.hsp.netty.groupchat.v1;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

/**
 * @Author CandyWall
 * @Date 2020/11/12--19:32
 * @Description 使用netty实现群聊服务器端
 */
public class GroupChatServer {
    private final int port;   //监听端口

    public GroupChatServer(int port) {
        this.port = port;
    }

    //编写run方法，处理客户端的请求
    public void run() {
        //创建两个线程组
        NioEventLoopGroup bossGroup = new NioEventLoopGroup(1);
        NioEventLoopGroup workerGroup = new NioEventLoopGroup(1);
        ServerBootstrap serverBootstrap = new ServerBootstrap();
        serverBootstrap.group(bossGroup, workerGroup)
                .channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG, 100)
                .childOption(ChannelOption.SO_KEEPALIVE, true)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ChannelPipeline pipeline = ch.pipeline();
                        //传输String类型的消息，必须要添加String的编解码器，否则，消息无法传输
                        //向Pipeline中加入一个解码器
                        pipeline.addLast("decoder", new StringDecoder());
                        //在Pipeline中加入一个编码器
                        pipeline.addLast("encoder", new StringEncoder());
                        //在Pipeline中加入自己的业务处理Handler
                        pipeline.addLast(new top.jacktgq.hsp.netty.groupchat.v1.GroupChatServerHandler());
                    }
                });
        try {
            System.out.println("Netty聊天服务器启动...");
            ChannelFuture channelFuture = serverBootstrap.bind(port).sync();

            //监听关闭
            channelFuture.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }

    }

    public static void main(String[] args) {
        new GroupChatServer(8888).run();
    }
}
